package com.hmall.transport.netty.client;


import com.hmall.enums.CompressTypeEnum;
import com.hmall.enums.SerializationTypeEnum;
import com.hmall.enums.ZkServiceEnum;
import com.hmall.extension.ExtensionLoader;
import com.hmall.factory.SingletonFactory;
import com.hmall.provider.ChannelProvider;
import com.hmall.provider.Impl.ZkChannelProvider;
import com.hmall.transport.RpcRequestTransport;
import com.hmall.transport.netty.codec.RpcMessageDecoder;
import com.hmall.transport.netty.codec.RpcMessageEncoder;
import com.hmall.remoting.constants.RpcContants;
import com.hmall.remoting.dto.RpcMessage;
import com.hmall.remoting.dto.RpcRequest;
import com.hmall.remoting.dto.RpcResponse;
import com.hmall.zookeeper.ServiceDiscovery;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.timeout.IdleStateHandler;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

import java.net.InetSocketAddress;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

@Slf4j
public class NettyRpcClient implements RpcRequestTransport {

    private final ServiceDiscovery serviceDiscovery;
    private final Bootstrap bootstrap;
    private final EventLoopGroup eventLoopGroup;
    private final ChannelProvider channelProvider;
    private final UnprocessedRequests unprocessedRequests;

    public NettyRpcClient(){
        bootstrap = new Bootstrap();
        eventLoopGroup = new NioEventLoopGroup();
        bootstrap.group(eventLoopGroup)
                .channel(NioSocketChannel.class)
                .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 500000)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel sc) throws Exception {
                        sc.pipeline().addLast(new IdleStateHandler(0, 5, 0, TimeUnit.SECONDS));
                        sc.pipeline().addLast(new RpcMessageEncoder());
                        sc.pipeline().addLast(new RpcMessageDecoder());
                        sc.pipeline().addLast(new NettyRpcClientHandler());

                    }
                });
        serviceDiscovery = ExtensionLoader.getExtensionLoader(ServiceDiscovery.class).getExtension(ZkServiceEnum.discovery.getClazz());
        channelProvider = SingletonFactory.getInstance(ZkChannelProvider.class);
        unprocessedRequests = SingletonFactory.getInstance(UnprocessedRequests.class);
    }

    @SneakyThrows
    public Channel doConnect(InetSocketAddress address) {
        CompletableFuture<Channel> completableFuture = new CompletableFuture<>();
        bootstrap.connect(address).addListener((ChannelFutureListener) future -> {
            if (future.isSuccess()) {
                log.info("The client has connected [{}] successful!", address.toString());
                completableFuture.complete(future.channel());
            } else {
                Throwable cause = future.cause();
                log.error("Connection to [{}] failed: {}", address, cause.getMessage(), cause);
                completableFuture.completeExceptionally(cause);
            }
        });
        return completableFuture.get();
    }

    public Object sendRpcRequest(RpcRequest rpcRequest) throws ExecutionException, InterruptedException {
        CompletableFuture<RpcResponse<Object>> resultFuture = new CompletableFuture<>();
        InetSocketAddress inetSocketAddress = serviceDiscovery.lookupService(rpcRequest);//服务拉取并挑选（已实现负载均衡）
        Channel channel = getChannel(inetSocketAddress);
        if (channel.isActive()) {
            unprocessedRequests.put(rpcRequest.getRequestId(), resultFuture);
            RpcMessage rpcMessage = RpcMessage.builder()
                    .data(rpcRequest)
                    .messageType(RpcContants.REQUEST_TYPE)
                    .codec(SerializationTypeEnum.HESSIAN.getCode())
                    .compress(CompressTypeEnum.GZIP.getCode())
                    .build();
            channel.writeAndFlush(rpcMessage).addListener((ChannelFutureListener) future -> {
                if (future.isSuccess()) {
                    log.info("client send message: [{}]", rpcMessage);
                }else {
                    resultFuture.completeExceptionally(future.cause());
                    log.error("Send failed:", future.cause());
                }
            });
        }
        return resultFuture;
    }

    public Channel getChannel(InetSocketAddress address) throws ExecutionException, InterruptedException {
        Channel channel = channelProvider.getChannel(address);
        if (channel == null) {
            channel = doConnect(address);
            channelProvider.setChannel(address, channel);
        }
        return channel;
    }
}
